package com.xm.servlet;

import com.xm.biz.UsersBiz;
import com.xm.biz.impl.UsersBizImpl;
import com.xm.po.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @author xie'lin'feng
 * @date 2020-08-07-15:05
 * @description 用户处理器
 */
@WebServlet("/usersLogin")
public class UsersLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //获取用户名
        String name = req.getParameter("username");
        //获取用户密码
        String pwd = req.getParameter("password");
        UsersBiz usersBiz = new UsersBizImpl();
        //得到用户信息
        Users users = usersBiz.login(name, pwd);
        if (users!=null){
            //将用户信息存入session中
            users.setCreateTime(new Date());
            usersBiz.updateLastLoginTime(users);
            HttpSession session = req.getSession();
            session.setAttribute("user", users);
            //重定向
            resp.sendRedirect("load");
        }else {
            req.setAttribute("name",name);
            req.setAttribute("msg","用户与密码不匹配!");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
